//
//  mttImage.m
//  mtt
//
//  Created by Gerfried Mikusch on 13.07.10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "mttImage.h"
#import "UIImage-Alpha.h"
#import "mttPoint.h"


@implementation mttImage


@synthesize tapRecognizer, tapRecTwoFingers, longPressRecognizer, panRecognizer, rotationRecognizer, pinchRecognizer, pinPoints, alphaMask, alphaMaskWidth, delegate, imagekey;

int pinPointKey = 0;
CGPoint hitPoint;
CGPoint hitPointWindow;


#pragma mark -
#pragma mark Alpha Mask


/*- (NSData *)alphaMask
{
    if (alphaMask == nil){
        
        self.alphaMask = [self.image alphaData];
        self.alphaMaskWidth = [self.image size].width;
        
    }
    return alphaMask;
}
 */

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event; 
{
	
	
		if ( (point.x > self.frame.size.width) || (point.y > self.frame.size.height) 
			|| point.x < 0 || point.y < 0){
			return nil;
		}
		NSData *rawData = [self alphaMask];  // caching of alpha Mask
		if (rawData){
			NSUInteger index = point.x + (point.y * alphaMaskWidth);
			char *rawDataBytes = (char *)[rawData bytes];
			//NSLog(@"xy:%lf:%lf->%d", point.x, point.y, rawDataBytes[index]);        
			return (rawDataBytes[index] == 0) ? nil : self;
		}
	
	
	return self;

}

/*
- (void)setImage:(UIImage *)image
{
    self.alphaMask = nil;
    [super setImage:image];
}
*/


#pragma mark -
#pragma mark gesture recognizing

// Ein TAP bringt das bild nach vorne!
- (void)handleTap:(UITapGestureRecognizer *)recognizer {
	if (recognizer.state == UIGestureRecognizerStateRecognized) {
		[delegate bringViewToFront:self];
		[delegate bringOptionViewToFront];
	}
}

// Touch and hold bring das menü!
-(void)handleLongPress:(UILongPressGestureRecognizer *)recognizer {
	[delegate bringViewToFront:self];
	[delegate bringOptionViewToFront];
	
	if (recognizer.state == UIGestureRecognizerStateBegan) {
		UIActionSheet *longTapMenu = [[UIActionSheet alloc] initWithTitle:nil 
																 delegate:self 
														cancelButtonTitle:nil 
												   destructiveButtonTitle:nil 
														otherButtonTitles:@"Pin", @"Set as Background", @"Remove", nil];
		
		
		hitPoint = [recognizer locationInView:self];
		hitPointWindow = [recognizer locationInView:nil];
		
		NSLog(@"hitPoint: x: %f, y: %f", hitPoint.x, hitPoint.y);
		[longTapMenu showFromRect:CGRectMake(hitPoint.x, hitPoint.y, 10, 10) inView:self animated:YES];
		[longTapMenu release];
		
	}
}


// Bewegt das Bild
-(void)handlePan:(UIPanGestureRecognizer *)recognizer {
	[delegate bringViewToFront:self];
	[delegate bringOptionViewToFront];
	
	if (recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) {
		
		CGPoint translation = [recognizer translationInView:self.superview];
		[self setCenter:CGPointMake(self.center.x + translation.x, self.center.y + translation.y)];
		[recognizer setTranslation:CGPointZero inView:self.superview];
		 
	}
	
}

// Rotiert das Bild
- (void)handleRotation:(UIRotationGestureRecognizer *)recognizer {
	[delegate bringViewToFront:self];
	[delegate bringOptionViewToFront];
	
    if ([recognizer state] == UIGestureRecognizerStateBegan || [recognizer state] == UIGestureRecognizerStateChanged) {
        self.transform = CGAffineTransformRotate(self.transform, [recognizer rotation]);
        [recognizer	setRotation:0];
    }
	
	
}

// Skaliert das Bild
- (void)handlePinch:(UIPinchGestureRecognizer *) recognizer {
	[delegate bringViewToFront:self];
	[delegate bringOptionViewToFront];
	
	if (recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) {
		self.transform = CGAffineTransformScale(self.transform, recognizer.scale, recognizer.scale);
		recognizer.scale = 1;
	}
}



- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return YES;
}


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    
	// Pan, Pinch und Rotation sollen simultan laufen. Man könnte auch darüber nachdenken das draggen mit zwei fingern zu ermöglichen!
	if (gestureRecognizer == self.pinchRecognizer ||
		gestureRecognizer == self.rotationRecognizer ||
		gestureRecognizer == self.panRecognizer ||
		otherGestureRecognizer == self.pinchRecognizer ||
		otherGestureRecognizer == self.rotationRecognizer ||
		otherGestureRecognizer == self.panRecognizer) {
		return YES;
	}
	return NO;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
		return YES;
}

-(void)setGestureRecognizersEnabled:(BOOL)enabled {

	NSArray *imgRecognizers	= self.gestureRecognizers;
	for (int i=0; i<imgRecognizers.count; i++) {
		[(UIGestureRecognizer *)[imgRecognizers objectAtIndex:i] setEnabled:enabled];
	}
	
}

#pragma mark -
#pragma mark Actions & Transformations

-(void)actionSheet:(UIActionSheet *)longTapMenu clickedButtonAtIndex:(NSInteger)buttonIndex {
	
	switch (buttonIndex) {
			
	    //Pin Button
		case 0:
			
			NSLog(@"hitpoint x: %f, hitpoint y: %f", hitPoint.x, hitPoint.y);
			
			[delegate performPinOnImages:hitPointWindow withCallerId:self.imagekey];
			
			break;
			
		//Set Background
		case 1:
			[delegate setMttBackground:self];
			[self removeFromSuperview];
			break;
			
		//Remove Image
		case 2:
			[self removeFromSuperview];
			[delegate removeImage:imagekey];
			break;

	}
}


-(void)setPin:(mttPoint *)pin {
	NSLog(@"in setPin");
	
	//Füge das den pin dem dictionary hinzu
	
	[pinPoints setObject:pin forKey:[NSNumber numberWithInt:pin.pinID]];
		
}


#pragma mark -
#pragma mark init & dealloc

- (id)initWithImage:(UIImage *)image {
	
	CGRect rect = CGRectMake(0, 0, 0, 0);
	rect.size = image.size;
	
	
	self = [super initWithFrame:rect];
	
	if (self != nil) {
		img = CGImageRetain(image.CGImage);
		
		/*
		NSUInteger length = rect.size.width * rect.size.height * 1;
		NSMutableData *data = [NSMutableData dataWithLength:length];
		CGContextRef context = CGBitmapContextCreate([data mutableBytes], rect.size.width, rect.size.height, 8, rect.size.width, NULL, kCGImageAlphaOnly);
		CGContextSetBlendMode(context, kCGBlendModeCopy);
		//CGContextDrawImage(context, rect, img);
		CGContextRelease(context);
		
		CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((CFMutableDataRef)data);
		maskingImage = CGImageMaskCreate(rect.size.width, rect.size.height, 8, 8, rect.size.width, dataProvider, NULL, YES);
		CGDataProviderRelease(dataProvider);
		*/
		
	
		//[super initWithImage:image];
	
		[self setUserInteractionEnabled:YES];
		[self setMultipleTouchEnabled:YES];
	
		pinPoints = [[NSMutableDictionary alloc] init];
	
		UIGestureRecognizer *recognizer;
	
		//recognizer für taps mit einem Finger
		recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
		[self addGestureRecognizer:recognizer];
		self.tapRecognizer = (UITapGestureRecognizer *)recognizer;
		self.tapRecognizer.numberOfTouchesRequired = 1;
		recognizer.delegate = self;
		[recognizer release];
	
		//recognizer für taps mit zwei Finger
		recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
		[self addGestureRecognizer:recognizer];
		self.tapRecTwoFingers = (UITapGestureRecognizer *)recognizer;
		self.tapRecTwoFingers.numberOfTouchesRequired = 2;
		recognizer.delegate = self;
		[recognizer release];
	
		//recognizer für longpress (touch & hold)
		recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
		[self addGestureRecognizer:recognizer];
		self.longPressRecognizer = (UILongPressGestureRecognizer *) recognizer;
		recognizer.delegate = self;
		[recognizer release];
	
		//recognizer für pans -> dragging
		recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
		[self addGestureRecognizer:recognizer];
		self.panRecognizer = (UIPanGestureRecognizer *)recognizer;
		self.panRecognizer.maximumNumberOfTouches = 2;
		recognizer.delegate = self;
		[recognizer release];
	
		//recognizer für Rotations
		recognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotation:)];
		[self addGestureRecognizer:recognizer];
		self.rotationRecognizer = (UIRotationGestureRecognizer *)recognizer;
		recognizer.delegate = self;
		[recognizer release];
	
		//recognizer für pinches -> skalieren
		recognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
		[self addGestureRecognizer:recognizer];
		self.pinchRecognizer = (UIPinchGestureRecognizer *)recognizer;
		recognizer.delegate = self;
		[recognizer release];
	
	}
	self.opaque = NO;
	return self;
}


-(void)drawRect:(CGRect)rect {
	
	CGContextRef context = UIGraphicsGetCurrentContext();
	
	//CGContextDrawImage(context, rect, img);
	
	//CGFloat height = self.bounds.size.height;
	//CGContextTranslateCTM(context, 0.0, height);
	//CGContextScaleCTM(context, 1.0, -1.0);
	
	//Innere Füllung!!!!!
	CGContextSetRGBFillColor(context, 0.3, 0.8, 0.1, 1);
	//CGContextSaveGState(context);
	
	CGContextClipToMask(context, rect, img);
	
	
	CGContextFillRect(context, self.bounds);
	//CGContextRestoreGState(context);
	
	
}

  
- (void) dealloc {
	
	CGImageRelease(maskingImage);
	CGImageRelease(alphaImage);
	
	
	[tapRecognizer release];
	[tapRecTwoFingers release];
	[longPressRecognizer release];
	[panRecognizer release];
	[rotationRecognizer release];
	[pinchRecognizer release];
	[super dealloc];
	
}

@end
